# import requests
import re
# from urllib import parse
# from lxml import etree
# from threading import Thread
from multiprocessing.pool import ThreadPool
# import time
import json
import os

from .my_base import MyBase

class DownLoadVideo(MyBase):

    def get_ts_video_save(self,video_ts,url_host='https://mivideo.g.mi.com/',target=''): #下载ts视频代码封装，用于多线程
        video_ts_name = video_ts.split('/')[-1]
        if target:
            video_ts_url = url_host + target + video_ts
        else:
            video_ts_url = url_host + video_ts
        print(video_ts_url)
        content = self.request_url(video_ts_url).content  # requests获取视频
        self.save_file('E:\pythonGit\qiannv\\' + video_ts_name, content, 'wb')  # 保存片段视频

    def save_file_two(self,path_dir,name,content):
        try:
            os.makedirs(path_dir)
        except FileExistsError:
            pass
        filename =path_dir+'/'+name+'.mp4'
        print(filename+'---->正在保存！')
        with open(filename,'wb') as f:
            f.write(content)
        print('{}下载结束！'.format(name))

    def download_video(self,title,video_url,keyword):
        path_dir = r'E:/动漫/{}'.format(keyword)
        # self.mk_file(path_dir)
        name = keyword + '-' + title
        print('{}正在下载中...'.format(name))
        content = self.request_url(video_url).content
        # content = b'aaa'
        self.save_file_two(path_dir, name, content)

    def parse_page_two(self,keyword,a): #没有blob加密
        url = 'http://www.zkk7.com/search/-------------.html?wd={}'.format(keyword)
        response = self.request_url(url)
        url_video = self.my_xpath(response.text, '//div[@class="thumb"]/a/@href')
        video_name = self.my_xpath(response.text, '//div[@class="detail"]/h3[@class="title"]/a/text()')
        # print(url_video,video_name)
        if url_video and video_name:
            for url,name in zip(url_video,video_name):
                pool = ThreadPool(10)
                # file_dir = 'E:\\动漫\\{}'.format(name)
                # self.mk_file(file_dir)
                video_url_ = 'http://www.zkk7.com' + url
                resp_video = self.request_url(video_url_)
                video_url_list = ['http://www.zkk7.com' + i for i in
                                  self.my_xpath(resp_video.text, '//*[@id="playlist{}"]/ul/li/a/@href'.format(a))]
                video_name_list = self.my_xpath(resp_video.text, '//*[@id="playlist1"]/ul/li/a/text()')
                # print(name,video_url_list,video_name_list)
                for url_v, name_v in zip(video_url_list, video_name_list):
                    # if name_v in ['第01集', '第02集', '第03集', '第04集', '第05集']:
                    #     continue
                    result = self.request_url(url_v)
                    # url_target_page = self.is_empty(self.my_xpath(result.text,'//*[@id="dplayer"]/div[2]/video/@src'))
                    # print(url_target_page)
                    # if 'blob' in url_target_page:
                    #     raise Exception('视频已经加密，请用第二种方式下载~')
                    item_str = re.findall(r'var player_data=({.*?"note":"".*?})</script>', result.text)[0]
                    item = json.loads(item_str)
                    url_shipin = item.get('url')
                    if 'mp4' in url_shipin:
                        pool.apply_async(self.download_video,args=(name_v,url_shipin,name))
                pool.close()
                pool.join()
        else:
            raise Exception('没有找到相关网址！')
    def parse_page_one(self,keyword,a): #blob加密
        url = 'http://www.zkk7.com/search/-------------.html?wd={}'.format(keyword)
        response = self.request_url(url)
        url_video = self.is_empty(self.my_xpath(response.text,'//div[@class="thumb"]/a/@href'))
        # print(url_video)
        if url_video:
            url_video = 'http://www.zkk7.com'+ url_video
            resp_video = self.request_url(url_video)
            video_url_list = ['http://www.zkk7.com'+i for i in self.my_xpath(resp_video.text,'//*[@id="playlist{}"]/ul/li/a/@href'.format(a))]
            video_name_list = self.my_xpath(resp_video.text,'//*[@id="playlist1"]/ul/li/a/text()')
            print(video_url_list)
            for url_v,name_v in zip(video_url_list,video_name_list):
                # if name_v in ['第01集','第02集','第03集','第04集','第05集']:
                #     continue
                result = self.request_url(url_v)
                item_str = re.findall(r'var player_data=({.*?"note":"".*?})</script>',result.text)[0]
                item = json.loads(item_str)
                del item_str
                url_video_m3u8 = item.get('url')
                print('----------->'+url_video_m3u8)
                url_video_m3u8 = url_video_m3u8.replace('hls.aoxtv.com/','')
                result_m3u8 = self.request_url(url_video_m3u8).text
                print(result_m3u8)
                m3u8_url = re.findall(r'\n(.*?\.m3u8)',result_m3u8)[0]
                if '/ppvod' not in m3u8_url:
                    url_host = url_video_m3u8.replace('index.m3u8','')
                    target = '{}/hls/'.format(m3u8_url.split('/')[0])
                else:
                    target = ''
                    url_host = url_video_m3u8.split('/2')[0]
                video_u = url_host + m3u8_url #meixianwan
                video_name = keyword + '-' + name_v + '.mp4'
                self.download_m3u8(video_u, url_host, video_name,target) #'800kb/hls/'
                # break
        else:
            print('没有搜索到相关内容。')

    def download_m3u8(self,video_m3u8_url,url_host,video_name,target =''): #樱花动漫 http://www.zkk7.com/
        pool = ThreadPool(10)
        result = self.request_url(video_m3u8_url).text  # m3u8文件内容
        m3u8_name = video_m3u8_url.split('/')[-1]
        dir_name = 'E:\pythonGit\qiannv\\' + m3u8_name  # 保存m3u8文件的全路径
        video_ts_list = re.findall(r',\n(.*?.ts)', result)  # 获取片段视频地址
        file_ts = video_ts_list[0].split('/')
        video_ts_list = self.take_list(video_ts_list)
        if len(file_ts) != 1:
            target = self.is_empty(re.findall(r',\n(.*/).*?.ts', result))
            result = result.replace(target, '')
        self.save_file(dir_name, result, 'w')
        print(video_ts_list)
        for video_ts in video_ts_list:
            video_ts = target + video_ts
            pool.apply_async(self.get_ts_video_save, args=(video_ts,url_host))  # 将下载片段视频任务添加到线程池
        pool.close()
        pool.join()
        m = self.agin_get_ts_url(video_ts_list,url_host,target)  # 补存下载遗漏
        if m == 0:
            self.hecheng_video(video_name, m3u8_name)  # 合成视频
            self.del_ts_video((video_ts_list,m3u8_name),'E:\pythonGit\qiannv')
        else:
            print('缺少ts_文件。')

    def hecheng_video(self,video_name,m3u8_name): #合成视频
        print('正在合成视频...')
        video_save_dir = 'E:\pythonGit\qiannv\\dm_video'
        self.mk_file(video_save_dir)
        video_save_dir = os.path.join(video_save_dir, video_name)
        print(video_save_dir)
        self.run_cmd(m3u8_name, video_save_dir, 'E:\pythonGit\qiannv')  #这里还需要写统计文件的个数，与ts的列表对比

    def agin_get_ts_url(self,ts_list,ts_host,target=''): #如果ts_url下载的视频片段有遗漏，补存下载  最好再递归下
        m = 0 #这个参数用来判断视频片段下载是否齐全，若为0则代表ts_视频片段已经下载齐全
        while m<=6:
            files = os.listdir('E:\pythonGit\qiannv')
            bianliang = set(ts_list) - set(files)
            if bianliang:
                for video_ts in bianliang:
                    self.get_ts_video_save(video_ts,ts_host,target)
                    m+=1
            else:
                print('ts_视频片段已经下载齐全。。。')
                m = 0
                break
        return m

    def del_ts_video(self,tuple_ts,current_dir): #删除ts文件
        video_ts_list,m3u8_name = tuple_ts
        video_ts_list.append(m3u8_name)
        for video_ts_name in video_ts_list:
            del_dir = os.path.join(current_dir, video_ts_name)
            # print(del_dir)
            if os.path.exists(del_dir):
                os.remove(del_dir)

    def run_cmd(self,m3u8_url,video_dir_name,save_dir): #执行cmd命令
        os.chdir(save_dir) #切换目录
        mingling = 'ffmpeg -allowed_extensions ALL -protocol_whitelist "file,http,crypto,tcp" -i {} -c copy {}'.format(m3u8_url,video_dir_name)
        os.system(mingling)

    def take_moshi(self,keyword,moshi):
        try:
            self.parse_page_two(keyword,moshi)
        except Exception as e:
            print(e)
            self.parse_page_one(keyword,moshi)

if __name__ == '__main__':
    gi = DownLoadVideo()
    # gi.parse_page_two('魔法科高校的劣等生',1) #后面参数代表模式 1和2
    # gi.parse_page_two('甜蜜惩罚 我是看守专用宠物',1) #后面参数代表模式 1和2
    gi.parse_page_two('日常系的异能战斗',1) #后面参数代表模式 1和2
    # gi.parse_page_one('与僧侣交合的色欲之夜',1) #后面参数代表模式 1和2
    # gi.parse_page_two('噬血狂袭',1) #后面参数代表模式 1和2